/*
 * ========================================================
 * Copyright(c) 2014 杭州偶尔科技-版权所有
 * ========================================================
 * 本软件由杭州偶尔科技所有, 未经书面许可, 任何单位和个人不得以
 * 任何形式复制代码的部分或全部, 并以任何形式传播。
 * 公司网址
 * 
 * 			http://www.kkkd.com/
 * 
 * ========================================================
 */
package com.simon.mengkou.ui.activity;

import android.content.Intent;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.ouertech.android.agm.lib.base.future.core.AgnettyFuture;
import com.ouertech.android.agm.lib.base.future.core.AgnettyResult;
import com.ouertech.android.agm.lib.base.utils.UtilDevice;
import com.ouertech.android.agm.lib.base.utils.UtilList;
import com.ouertech.android.agm.lib.base.utils.UtilString;
import com.ouertech.android.agm.lib.ui.base.MenuImg;
import com.simon.mengkou.R;
import com.simon.mengkou.data.bean.base.Follow;
import com.simon.mengkou.data.bean.base.Image;
import com.simon.mengkou.data.bean.base.Product;
import com.simon.mengkou.data.bean.base.Shop;
import com.simon.mengkou.data.bean.base.Store;
import com.simon.mengkou.data.enums.EDirection;
import com.simon.mengkou.data.pref.OuerPreferences;
import com.simon.mengkou.future.base.OuerFutureListener;
import com.simon.mengkou.system.constant.CstOuer;
import com.simon.mengkou.system.global.OuerApplication;
import com.simon.mengkou.system.global.OuerDispatcher;
import com.simon.mengkou.ui.adapter.ProductActivityAdapter;
import com.simon.mengkou.ui.adapter.ProductImageAdapter;
import com.simon.mengkou.ui.adapter.ProductOrderAdapter;
import com.simon.mengkou.ui.base.BaseSocialShareActivity;
import com.simon.mengkou.ui.dialog.ShareDialog;
import com.simon.mengkou.ui.view.BaseViewPager;
import com.simon.mengkou.ui.view.LoopPageIndicator;
import com.simon.mengkou.ui.view.LoopViewPager;
import com.simon.mengkou.ui.view.LoopViewPagerAdapter;
import com.simon.mengkou.ui.view.MyGridView;
import com.simon.mengkou.utils.UtilOuer;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author : Zhenshui.Xia
 * @since : 2016/3/14.
 * desc    : 商品详情界面
 */
public class ProductDetailActivity extends BaseSocialShareActivity
        implements PullToRefreshBase.OnRefreshListener2<ListView>{
    //商品id
    private String mProductId;
    //店铺图标
//    private SimpleDraweeView mSdvShopIcon;
    //店铺标题
//    private TextView mTvShopName;
    //单张商品图片
    private SimpleDraweeView mSdvImage;
    //多张商品图片
    private LoopViewPager mLvpPager;
	private LoopViewPagerAdapter mPagerAdapter;
	private LoopPageIndicator mLvpIndicator;
	private ProductImageAdapter mImageAdapter;
    //标题
    private TextView mTvTitle;
    //价格
    private TextView mTvPrice;
    //原价
    private TextView mTvMarketPrice;
    //分仓
    private TextView mTvCompartment;
    private LinearLayout mLlCompartmentRoot;
    //内容
    private WebView mWvContent;
    //美国直邮
//    private TextView mTvDirectUS;
    //活动
//    private MyGridView mMgvActivity;
//    private ProductActivityAdapter mActivityAdapter;
//    private View mViewLine;
//    private View mViewLine2;
    //晒单
    private TextView mTvOrderHeader;
    @Bind(R.id.common_pulltorefresh_id_list)
    PullToRefreshListView mPtrView;
    private String mMaxId = CstOuer.PAGE.DEFAULT_MAXID;
    private ProductOrderAdapter mOrderAdapter;
    private Product mProduct;
    //拼团预售
    @Bind(R.id.product_id_join_tuan)
    TextView mTvTuan;

    //购物车红点
    @Bind(R.id.product_id_cart_dot)
    TextView mTvNum;

    @Override
    protected void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);
        if (Intent.ACTION_VIEW.equals(getIntent().getAction())) {
            Uri uri = getIntent().getData();
            mProductId = uri.getQueryParameter(CstOuer.KEY.ID);
        } else {
            mProductId = getIntent().getStringExtra(CstOuer.KEY.ID);
        }
    }

    @Override
    protected void initTop() {
        setTitle(R.string.product_title);
        setNavigation(R.drawable.common_ic_left_nav);

        //分享
        MenuImg img = new MenuImg.MenuImgBuilder(this)
            .setTitle(R.string.common_share)
            .setIcon(R.drawable.common_ic_share)
            .setListener(new MenuItem.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    showShareDialog();
                    return false;
                }
            }).build();

        addMenu(img);
    }

    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_product_detail);
    }

    @Override
    protected void initViews() {
        ButterKnife.bind(this);

        registerAction(CstOuer.BROADCAST_ACTION.ADD_CART_ACTION);
        int num = OuerApplication.mPreferences.getCartProductNum();
        if(num == 0) {
            mTvNum.setVisibility(View.GONE);
        } else {
            mTvNum.setVisibility(View.VISIBLE);
            mTvNum.setText(String.valueOf(num));
        }

        mPtrView.setOnRefreshListener(this);
        mPtrView.setMode(PullToRefreshBase.Mode.DISABLED);
        mPtrView.setTag(false);

        //头部
        View header = LayoutInflater.from(this).inflate(R.layout.layout_product_header, null);
        mSdvImage = (SimpleDraweeView)header.findViewById(R.id.product_id_image);
        mLvpIndicator = (LoopPageIndicator)header.findViewById(R.id.product_id_indicator);
		mLvpPager = (LoopViewPager) header.findViewById(R.id.product_id_banner);
        mLvpPager.setAutoScroll(false);

        RelativeLayout rlRoot = (RelativeLayout) header.findViewById(R.id.product_id_banner_root);
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) rlRoot.getLayoutParams();
        params.width = UtilDevice.getDevice(this).getWidth();
        params.height = params.width;

        mTvTitle = (TextView)header.findViewById(R.id.product_id_title);
        mTvPrice = (TextView)header.findViewById(R.id.product_id_price);
        mTvMarketPrice = (TextView)header.findViewById(R.id.product_id_market_price);
        mLlCompartmentRoot = (LinearLayout)header.findViewById(R.id.product_id_compartment_root);
        mTvCompartment = (TextView) header.findViewById(R.id.product_id_compartment);
        mTvCompartment.setOnClickListener(this);
        mWvContent = (WebView) header.findViewById(R.id.product_id_content_url);

        mTvOrderHeader = (TextView) header.findViewById(R.id.product_id_order_header);

        mPtrView.getRefreshableView().addHeaderView(header);

        mOrderAdapter = new ProductOrderAdapter(this);
        mPtrView.setAdapter(mOrderAdapter);

        //首次失败重试
        setOnRetryListener(new OnRetryListener() {
            @Override
            public void onRetry() {
                getProductDetail();
            }
        });

        //获取数据
        getProductDetail();
        cartProductNum();
    }


    @Override
    protected void onReceive(Intent intent) {
        super.onReceive(intent);
        String action = intent.getAction();
        if(CstOuer.BROADCAST_ACTION.ADD_CART_ACTION.equals(action)) {
            int num = intent.getIntExtra(CstOuer.KEY.CART_NUM, OuerApplication.mPreferences.getCartProductNum());
            if(num == 0) {
                mTvNum.setVisibility(View.GONE);
            } else {
                mTvNum.setVisibility(View.VISIBLE);
                mTvNum.setText(String.valueOf(num));
            }
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        //下拉刷新
        getData(CstOuer.PAGE.DEFAULT_MAXID, EDirection.REFRESH);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        //上拉加载更多
        getData(mMaxId, EDirection.LOADMORE);
    }

    /**
     * 获取商品详情
     */
    private void getProductDetail() {
        AgnettyFuture future = OuerApplication.mOuerFuture.getProductDetail(mProductId,
                new OuerFutureListener(this) {
                    @Override
                    public void onStart(AgnettyResult result) {
                        super.onStart(result);
                        setLoading(true);
                    }

                    @Override
                    public void onComplete(AgnettyResult result) {
                        super.onComplete(result);
                        setLoading(false);
                        mProduct = (Product) result.getAttach();
                        setProductDetail();
                        //获取数据
                        getData(CstOuer.PAGE.DEFAULT_MAXID, EDirection.REFRESH);
                    }

                    @Override
                    public void onException(AgnettyResult result) {
                        super.onException(result);
                        setRetry(true);
                    }

                    @Override
                    public void onNetUnavaiable(AgnettyResult result) {
                        super.onNetUnavaiable(result);
                        setRetry(true);
                    }
                });

        attachDestroyFutures(future);

    }

    /**
     * 获取商品晒单
     */
    private void getData(final String maxId, final int direction) {
        AgnettyFuture future = OuerApplication.mOuerFuture.getProductOrders(mProductId,
                maxId, CstOuer.PAGE.DEFAULT_MINID, CstOuer.PAGE.DEFAULT_SIZE,
                new OuerFutureListener(this){

                    @Override
                    public void onComplete(AgnettyResult result) {
                        super.onComplete(result);
                        mPtrView.onRefreshComplete();
                        List<Follow> datas = (List<Follow>) result.getAttach();

                        int count = UtilList.getCount(datas);
                        //设置最新的max id
                        if(count != 0) {
                            mMaxId = datas.get(count - 1).getId();
                        }

                        //数据已读取完
                        if(count < CstOuer.PAGE.DEFAULT_SIZE) {
                            mPtrView.setMode(PullToRefreshBase.Mode.DISABLED);
                        } else {
                            mPtrView.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
                        }

                        mOrderAdapter.addList(datas);

                        if(mOrderAdapter.getCount() == 0) {
                            mTvOrderHeader.setVisibility(View.GONE);
                        } else {
                            mTvOrderHeader.setVisibility(View.VISIBLE);
                        }
                    }

                    public void onNetUnavaiable(AgnettyResult result) {
                        super.onNetUnavaiable(result);
                        mPtrView.onRefreshComplete();
                    }

                    @Override
                    public void onException(AgnettyResult result) {
                        super.onException(result);
                        mPtrView.onRefreshComplete();
                    }
                });

        attachDestroyFutures(future);
    }

    /**
     * 设置数据
     */
    private void setProductDetail() {
        if(mProduct == null) {
            return;
        }


        //图片
        updateBanner(mProduct.getImageArray());

        //商品标题
        mTvTitle.setText(mProduct.getTitle());
        //价格
        mTvPrice.setText(getString(R.string.common_price,
                UtilOuer.formatPrice(mProduct.getPrice())));
        //原价
        mTvMarketPrice.setText(getString(R.string.common_price,
                UtilOuer.formatPrice(mProduct.getMarketPrice())));
        mTvMarketPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG );//中划线
        mTvMarketPrice.getPaint().setAntiAlias(true);

        //内容
//        mTvContent.setText(mProduct.getContent());
//        mWvContent.loadDataWithBaseURL(null, mProduct.getContent(), "text/html", CstCharset.UTF_8, null);
        mWvContent.loadUrl(mProduct.getContentUrl());

        //美国直邮
//        if(mProduct.isDirectUS()) {
//            mTvDirectUS.setVisibility(View.GONE);//暂时去掉
//        } else {
//            mTvDirectUS.setVisibility(View.GONE);
//        }
//
//        //活动
//        if(UtilList.isNotEmpty(mProduct.getActivities())) {
//            mActivityAdapter = new ProductActivityAdapter(this, mProduct.getActivities());
//            mMgvActivity.setAdapter(mActivityAdapter);
//        } else {
//            mMgvActivity.setVisibility(View.GONE);
//            mViewLine.setVisibility(View.GONE);
//            mViewLine2.setVisibility(View.GONE);
//        }

        //拼团预售
//        if(UtilString.isNotBlank(mProduct.getGroupbuyId())) {
//            mTvTuan.setVisibility(View.VISIBLE);
//            mTvTuan.setText(R.string.product_join_tuan);
//        } else if(UtilString.isNotBlank(mProduct.getPreSaleId())) {
//            mTvTuan.setVisibility(View.VISIBLE);
//            mTvTuan.setText(R.string.product_join_presale);
//        } else {
//            mTvTuan.setVisibility(View.INVISIBLE);
//        }

        if(mProduct.isCollected()) {
            mTvTuan.setText(R.string.product_join_cancel_tuan);
        } else {
            mTvTuan.setText(R.string.product_join_tuan);
        }

        //分仓
        if(mProduct.getStore() != null) {
            mLlCompartmentRoot.setVisibility(View.VISIBLE);
            mTvCompartment.setText(mProduct.getStore().getName());
        } else {
            mLlCompartmentRoot.setVisibility(View.GONE);
        }
    }


    /**
     * 更新商品图片
     * @param datas
     */
    private void updateBanner(List<Image> datas) {
        if (UtilList.isNotEmpty(datas)) {
            if(UtilList.getCount(datas) == 1) {
                OuerApplication.mImageLoader.loadImage(mSdvImage, datas.get(0).getUrl());
            } else {
                mLvpIndicator.initIndicator(0,
                        datas.size(),
                        R.drawable.common_ic_indicator_dot_normal,
                        R.drawable.common_ic_indicator_dot_focus);

                mImageAdapter = new ProductImageAdapter(this, datas);
                mPagerAdapter = new LoopViewPagerAdapter(mImageAdapter);
                mLvpPager.setInfinateAdapter(mPagerAdapter);

                mLvpPager.setOnPageChangeListener(new BannerPageChangeListener(datas.size()));
            }
        }
    }


    /**
	 *
	 * @author Zhenshui.Xia
	 *
	 */
	private class BannerPageChangeListener implements BaseViewPager.OnPageChangeListener {
		//
		public static final int SCROLL_STATE_IDLE = 0;
		//
		public static final int SCROLL_STATE_DRAGGING = 1;
		//
		public static final int SCROLL_STATE_SETTLING = 2;

		private int mSize;

		public BannerPageChangeListener(int size) {
			this.mSize = size;
		}

		@Override
		public void onPageScrollStateChanged(int state) {
			switch (state) {
				case SCROLL_STATE_IDLE:
					break;

				case SCROLL_STATE_DRAGGING:
					break;

				case SCROLL_STATE_SETTLING:
					break;
			}
		}

		@Override
		public void onPageScrolled(int position, float positionOffset,
				int positionOffsetPixels) {
		}

		@Override
		public void onPageSelected(int position) {
			int index = position % mSize;
			mLvpIndicator.refreshIndicator(index);

		}

	}



    @Override
    public void onClick(View v) {
        super.onClick(v);

        switch (v.getId()) {
            case R.id.product_id_compartment:
                if(mProduct != null && mProduct.getStore() != null) {
                    Store store = mProduct.getStore();
                    OuerDispatcher.presentProductCompartmentActivity(this, store.getId(), store.getName());
                }
                break;
            case R.id.share_id_qq://分享到qq
                shareProduct(SHARE_MEDIA.QQ);
                break;
            case R.id.share_id_wechat://分享到微信
                shareProduct(SHARE_MEDIA.WEIXIN);
                break;
            case R.id.share_id_sina://分享到新浪
                shareProduct(SHARE_MEDIA.SINA);
                break;
            case R.id.share_id_qzone://分享qq空间
                shareProduct(SHARE_MEDIA.QZONE);
                break;
            case R.id.share_id_circle://分享微信朋友圈
                shareProduct(SHARE_MEDIA.WEIXIN_CIRCLE);
                break;
        }
    }

    /**
     * 分享
     * @param platform
     */
    private void shareProduct(SHARE_MEDIA platform) {
        if(mProduct == null) {
            return;
        }

        share(platform, getString(R.string.app_name),
                mProduct.getTitle(), mProduct.getShareUrl(), mProduct.getImageArray().get(0).getUrl());
    }

    /**
     * 显示分享对话框
     */
    public void showShareDialog() {
        ShareDialog dialog = new ShareDialog(this, this);
        dialog.showAtLocation(mPtrView, Gravity.CENTER, 0, 0);
    }

    //加入购物车
    @OnClick(R.id.product_id_add_cart)
    public void addCart() {
        AgnettyFuture future = OuerApplication.mOuerFuture.cartAdd(
                mProductId, 1,
                new OuerFutureListener(this) {
                    @Override
                    public void onStart(AgnettyResult result) {
                        super.onStart(result);
                        setWaitingDialog(true);
                    }

                    @Override
                    public void onComplete(AgnettyResult result) {
                        super.onComplete(result);
                        setWaitingDialog(false);
                        Boolean flag = (Boolean) result.getAttach();
                        if(flag) {
                            UtilOuer.toast(ProductDetailActivity.this, R.string.product_add_cart_success);
                        } else {
                            UtilOuer.toast(ProductDetailActivity.this, R.string.product_add_cart_failure);
                        }
                    }

                    @Override
                    public void onException(AgnettyResult result) {
                        super.onException(result);
                        setWaitingDialog(false);
                        UtilOuer.showExceptionToast(ProductDetailActivity.this, result, R.string.product_add_cart_failure);
                    }

                    @Override
                    public void onNetUnavaiable(AgnettyResult result) {
                        super.onNetUnavaiable(result);
                        setWaitingDialog(false);
                    }
                });

        attachDestroyFutures(future);
    }

    //拼团
    @OnClick(R.id.product_id_join_tuan)
    public void joinTuan() {
        AgnettyFuture future = OuerApplication.mOuerFuture.addWish(
                mProduct.getId(), !mProduct.isCollected(),
                new OuerFutureListener(this) {
                    @Override
                    public void onStart(AgnettyResult result) {
                        super.onStart(result);
                        setWaitingDialog(true);
                    }

                    @Override
                    public void onComplete(AgnettyResult result) {
                        super.onComplete(result);
                        setWaitingDialog(false);
                        mProduct.setCollected(!mProduct.isCollected());
                        if(mProduct.isCollected()) {
                            mTvTuan.setText(R.string.product_join_cancel_tuan);
                            UtilOuer.toast(ProductDetailActivity.this, R.string.product_add_wish_success);
                        } else {
                            mTvTuan.setText(R.string.product_join_tuan);
                            UtilOuer.toast(ProductDetailActivity.this, R.string.product_cancel_wish_success);
                        }
                    }

                    @Override
                    public void onException(AgnettyResult result) {
                        super.onException(result);
                        setWaitingDialog(false);
                        if(mProduct.isCollected()) {
                            UtilOuer.showExceptionToast(ProductDetailActivity.this, result,
                                    R.string.product_cancel_wish_failure);
                        } else {
                            UtilOuer.showExceptionToast(ProductDetailActivity.this, result,
                                    R.string.product_add_wish_failure);
                        }
                    }

                    @Override
                    public void onNetUnavaiable(AgnettyResult result) {
                        super.onNetUnavaiable(result);
                        setWaitingDialog(false);
                    }
                });

        attachDestroyFutures(future);
    }

    //购物车
    @OnClick(R.id.product_id_cart)
    public void presentCart() {
        OuerDispatcher.presentCartActivity(this);
    }

    /**
     * 获取购物车商品数量
     */
    private void cartProductNum() {
        AgnettyFuture future = OuerApplication.mOuerFuture.cartProductNum(null);
        attachDestroyFutures(future);
    }

}
